import {
  EntitySubscriberInterface,
  EventSubscriber,
  InsertEvent,
  UpdateEvent,
} from 'typeorm';
import { CompanyEntity } from './entities/company.entity';
import { RecordCompanyEntity } from 'src/record_company/entities/record_company.entity';

@EventSubscriber()
export class CompanySubscriber
  implements EntitySubscriberInterface<CompanyEntity>
{
  listenTo() {
    return CompanyEntity;
  }
  // 新增
  async afterInsert(event: InsertEvent<CompanyEntity>) {
    const newRecord = event.manager.create(RecordCompanyEntity, {
      user_id: event.entity.user_id,
      company_id: event.entity.id,
      name: event.entity.name,
    });
    await event.manager.save(newRecord);
  }
  // 更新
  async afterUpdate(event: UpdateEvent<CompanyEntity>) {
    const entity = event.entity as CompanyEntity;
    const newRecord = event.manager.create(RecordCompanyEntity, {
      user_id: entity.user_id,
      company_id: entity.id,
      name: entity.name,
      is_update: 1,
    });
    await event.manager.save(newRecord);
  }
}
